import BASE_URL from './index'

//保证登录后再掉其他接口
let apiCacheList=[]
let isLogin=false
let loginUrl='/wechat/miniProgram/appCode/hwManage'
let ajax = (url, method, data?, header?) => {
    
    return new Promise((resolve, reject) => {
		let func= (Authorization)=>{
			uni.request({
			  url: BASE_URL + url,
			  data: data,
			  method: method,
			  header: {Authorization,...header},
			  success: async(res) => {

			    // 响应拦截处理
			    if (res.statusCode == 200) {
				  if(url==loginUrl){
					  isLogin=true;
					  let token=res.data.result.token
					  apiCacheList.forEach((fc)=>{
						  fc(token)
					  })
					  apiCacheList=[]
				  }
			      resolve(res.data);
			    } else if (res.statusCode == 404) {
			      // 404 请求页面不存在
			      resolve(res.data);
			    } else if (res.statusCode == 400) {
			      uni.showToast({
			      	icon:"none",
			      	title:res.data.message
			      })
			      reject(res);
			    }else{
				  reject(res);
				}
			    
				
			  },
			  fail: (error) => {
			    reject(error);
				
			    return;
			  },
			  complete: () => {
			  }
			})
		}
	  if(isLogin||url==loginUrl){
		  let token = uni.getStorageSync('token') || ''
		  func(token)
	  }else{
		  apiCacheList.push(func)
	  }
     
    })
}

// let _Request:any = {}

class _Request {
  get(url, data?, header?){
    return ajax(url, 'GET', data, header);
  }
  post(url, data?, _header?) {
      let header = _header? _header:{}
      header['Content-Type'] = 'application/json';
      return ajax(url, 'POST', data, header);
  }
  delete(url, data?, header?){
      return ajax(url, 'delete', data, header);
  }
  put(url, data?, header?){
      return ajax(url, 'put', data, header);
  }
}


export default _Request